import 'dart:convert' as convert;
import 'dart:io';

import 'package:flutter/foundation.dart';
import 'package:path_provider/path_provider.dart';
import 'package:shared_preferences/shared_preferences.dart';

DataStore dataStore = DataStore();

// 保存数据
class DataStore {
  Future<String> getDocumentPath() async {
    if (!(Platform.isAndroid || Platform.isIOS)) {
      return ".";
    }
    // 获取文档目录
    var appDocDir = await getApplicationDocumentsDirectory();
    return appDocDir.path;
  }

  static const String token = "AuthorizationToken";

  Future<void> setAuthorizationToken(String tokenStr) async {
    if (!(Platform.isAndroid || Platform.isIOS)) {
      return setValue(token, tokenStr);
    }
    SharedPreferences _prefs = await SharedPreferences.getInstance();
    _prefs.setString(token, tokenStr);
  }

  Future<String> getAuthorizationToken() async {
    if (!(Platform.isAndroid || Platform.isIOS)) {
      return getValue(token);
    }
    SharedPreferences _prefs = await SharedPreferences.getInstance();
    return _prefs.get(token);
  }

  static const String kvFile = "kvfile.txt";

  Future<void> setValue(String key, String value) async {
    var file = await _getFile('./$kvFile');
    var jsonStr = await file.readAsString();
    Map<String, dynamic> json = convert.jsonDecode(jsonStr);
    json[key] = value;
    file.writeAsString(convert.jsonEncode(json));
    return;
  }

  Future<String> getValue(String key) async {
    var file = await _getFile('./$kvFile');
    var jsonStr = await file.readAsString();
    Map<String, dynamic> json = convert.jsonDecode(jsonStr);
    if (json.containsKey(key)) {
      return json[key];
    }
    return "";
  }

  Future<File> _getFile(String path) async {
    var file = new File(path);
    if (!await file.exists()) {
      var file2 = await file.create(recursive: true);
      file2.writeAsString("{}");
      return file2;
    }
    return file;
  }
}
